package com.yequan.leetcode.linkedlist.mergeKLists_23;

import com.yequan.leetcode.linkedlist.ListNode;

/**
 * @author yequan
 * @date 2022/03/03 15:27
 **/
public class MergeKLists {

    public ListNode mergeKLists(ListNode[] lists) {
        ListNode res = null;
        for (ListNode listNode : lists) {
            res = mergeTwoLists(listNode, res);
        }
        return res;
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode preHead = new ListNode(-1);
        ListNode preNode = preHead;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                preNode.next = l1;
                l1 = l1.next;
            } else {
                preNode.next = l2;
                l2 = l2.next;
            }
            preNode = preNode.next;
        }
        preNode.next = l1 == null ? l2 : l1;
        return preHead.next;
    }

}
